package com.wwtech.epp.ui.activity.work.presenter;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;

import com.socks.library.KLog;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.data.api.HttpAPIWrapper;
import com.wwtech.epp.db.Friend;
import com.wwtech.epp.entity.BaseBack;
import com.wwtech.epp.entity.ProjectTask;
import com.wwtech.epp.ui.activity.work.NewProjectActivity;
import com.wwtech.epp.ui.activity.work.contract.NewProjectContract;
import com.wwtech.epp.utils.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

import static com.wwtech.epp.ui.activity.work.NewProjectActivity.RESULTOK;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: presenter of NewProjectActivity
 * @date 2017/09/01 22:09:47
 */
public class NewProjectPresenter implements NewProjectContract.NewProjectContractPresenter{

    HttpAPIWrapper httpAPIWrapper;
    private final NewProjectContract.View mView;
    private CompositeDisposable mCompositeDisposable;
    private NewProjectActivity mActivity;

    private ArrayList<ProjectTask> projectTaskArrayList = new ArrayList<>();   //项目的任务数的集合

    private ArrayList<Friend> projectManagers = new ArrayList<>();        //项目的负责人的集合
    private ArrayList<Friend> partPerson = new ArrayList<>();              //项目的参与人的集合
    private Friend tempFriend;

    @Inject
    public NewProjectPresenter(@NonNull HttpAPIWrapper httpAPIWrapper, @NonNull NewProjectContract.View view, NewProjectActivity activity) {
        mView = view;
        this.httpAPIWrapper = httpAPIWrapper;
        mCompositeDisposable = new CompositeDisposable();
        this.mActivity = activity;
    }
    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        if (!mCompositeDisposable.isDisposed()) {
             mCompositeDisposable.dispose();
        }
    }

    @Override
    public void init() {
        projectTaskArrayList = new ArrayList<>();
        projectManagers = new ArrayList<>();
        partPerson = new ArrayList<>();
        tempFriend = new Friend("", "-1", "", Uri.parse(""));
        tempFriend.setUserId("-1");
        projectManagers.add(tempFriend);
        partPerson.add(tempFriend);
        mView.setPersonData(projectManagers, partPerson);
    }

    @Override
    public void addProjectTask() {
        ProjectTask task = new ProjectTask();
        projectTaskArrayList.add(task);
        mView.setProjectTaskData(projectTaskArrayList);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == NewProjectActivity.CHECKMANAGE && resultCode == RESULTOK) {
            mView.onProjectManagerBack(ContainValue.projectManager);
        }
        if (requestCode == NewProjectActivity.CHECKPART && resultCode == RESULTOK) {
            partPerson = ContainValue.partPerson;
            mView.setPersonData(projectManagers, partPerson);
        }
        if (requestCode == NewProjectActivity.CHECKTASKMANAGE && resultCode == RESULTOK) {
            projectTaskArrayList.get(Integer.parseInt(data.getStringExtra("position"))).setPartPerson(ContainValue.tempManager);
            projectTaskArrayList.get(Integer.parseInt(data.getStringExtra("position"))).setCheck(true);
            mView.onProjectTaskManagerBaack();
        }
    }

    /**
     * "createTime": "2017-09-14T14:43:09.117Z",
     "createrId": 0,
     "deadline": "2017-09-14T14:43:09.117Z",
     "jobContent": "string",                  //不传
     "jobId": 0,
     "jobState": 0,
     "jobTitle": "string",
     "ownerId": 0,
     "projectId": 0,         //不传
     "state": 0
     * @param map
     */
    @Override
    public void packData(Map map) {
        KLog.i("准备数据中。。。。。。。");
        ArrayList<String> partnerList = new ArrayList<>();
        for (int i = 0; i < partPerson.size() - 1; i++) {
            partnerList.add(partPerson.get(i).getUserId());
        }
        ArrayList<Map> subTaskMap = new ArrayList<>();
        for (int i = 0; i < projectTaskArrayList.size(); i++) {
            Map<String, Object> tempMap = new HashMap<>();
//            tempMap.put("createTime", TimeUtil.timesTamp2YearMonthDay(Calendar.getInstance().getTimeInMillis()));
            tempMap.put("createrId", ContainValue.userLogin.getData().getUserId());
            tempMap.put("deadline", projectTaskArrayList.get(i).getEndTime());
//            tempMap.put("jobId", i);
            tempMap.put("jobContent", projectTaskArrayList.get(i).getDiscrab());
//            tempMap.put("jobState", 0);
            tempMap.put("jobTitle", projectTaskArrayList.get(i).getDiscrab());
            tempMap.put("ownerId", projectTaskArrayList.get(i).getPartPerson().getUserId());
//            tempMap.put("state", 0);
            subTaskMap.add(tempMap);
        }
        map.put("ownerUid",ContainValue.projectManager.getUserId());
        map.put("partner",partnerList);
        map.put("subJob",subTaskMap);
        JSONObject json=new JSONObject(map);
        KLog.i(json.toString());
        newProject(map);
    }

    @Override
    public void newProject(Map map) {
        KLog.i(map);
        mView.showProgressDialog();
        Disposable disposable = httpAPIWrapper.addProject(map)
                .subscribe(new Consumer<BaseBack>() {
                    @Override
                    public void accept(BaseBack baseBack) throws Exception {
                        //isSuccesse
                        KLog.i("onSuccesse");
                        mView.closeProgressDialog();
                        ToastUtil.displayShortToast("新建项目成功");
                        if (baseBack.getResultCode() == 0) {
                            AppConfig.getInstance().mAppActivityManager.finishActivity(NewProjectActivity.class);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //onError
                        KLog.i("onError");
                        mView.closeProgressDialog();
                        throwable.printStackTrace();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //onComplete
                        KLog.i("onComplete");
                    }
                });
        mCompositeDisposable.add(disposable);
    }

}